import React from 'react';
import { Card, Row, Col, Descriptions, Tag, Statistic, Space, Avatar, Divider, Typography, Button } from 'antd';
import {
  UserOutlined,
  TrophyOutlined,
  RiseOutlined,
  DashboardOutlined,
  FileTextOutlined,
  PhoneOutlined,
  DownOutlined,
  UpOutlined
} from '@ant-design/icons';
import type { Customer } from '../types';
import { formatAmount } from '../utils/numberFormat';

interface CustomerProfilePageProps {
  customer: Customer;
}

const CustomerProfilePage: React.FC<CustomerProfilePageProps> = ({ customer }) => {
  // 添加状态管理基金持仓显示
  const [showAllHoldings, setShowAllHoldings] = React.useState(false);

  // 解析 AI 摘要
  const aiSummary = React.useMemo(() => {
    try {
      return customer.ai_summary ? JSON.parse(customer.ai_summary) : null;
    } catch (error) {
      console.error('Failed to parse ai_summary:', error);
      return null;
    }
  }, [customer.ai_summary]);

  // 解析当前持仓配置
  const currentPosition = React.useMemo(() => {
    try {
      return customer.current_position ? JSON.parse(customer.current_position) : null;
    } catch (error) {
      console.error('Failed to parse current_position:', error);
      return null;
    }
  }, [customer.current_position]);

  // AI总结卡片
  const renderAISummary = () => (
    <Card
      title={
        <Space>
          <UserOutlined className="text-blue-600" />
          <span>客户AI总结</span>
        </Space>
      }
      className="mb-4"
    >
      <div className="space-y-4">
        <div>
          <h4 className="text-gray-700 font-medium mb-2">个性特征</h4>
          <p className="text-gray-600 leading-relaxed">{aiSummary?.['个性特征']}</p>
        </div>

        <div>
          <h4 className="text-gray-700 font-medium mb-2">投资风格</h4>
          <p className="text-gray-600 leading-relaxed">{aiSummary?.['投资风格']}</p>
        </div>

        <div>
          <h4 className="text-gray-700 font-medium mb-2">关键特质</h4>
          <div className="flex flex-wrap gap-2">
            {aiSummary?.['关键特质']?.map((trait: string, index: number) => (
              <Tag key={index} color="blue" className="mb-1">{trait}</Tag>
            ))}
          </div>
        </div>

        <div>
          <h4 className="text-gray-700 font-medium mb-2">风险承受能力</h4>
          <p className="text-gray-600 leading-relaxed">{aiSummary?.['风险承受能力']}</p>
        </div>
      </div>
    </Card>
  );

  // 资产配置概览卡片
  const renderAssetOverview = () => {
    // 动态生成资产配置数据
    const generatePortfolioData = () => {
      const colorMap = {
        '货币类': '#4F83F6',
        '固收类': '#4ADE80',
        '权益类': '#F59E0B',
        '另类': '#EF4444',
        'QDII': '#8B5CF6',
        '债券类': '#10B981',
        '股票类': '#F97316',
        '基金类': '#6366F1',
        '保险类': '#EC4899',
        '房地产': '#84CC16',
        '商品类': '#F59E0B',
        '加密货币': '#EF4444'
      };

      const portfolioData = [];

      // 遍历 currentPosition 的所有属性
      for (const [key, value] of Object.entries(currentPosition)) {
        let numValue: number | null = null;
        if (typeof value === 'string' && value.endsWith('%')) {
          numValue = parseFloat(value.replace('%', ''));
        } else if (typeof value === 'number') {
          numValue = value;
        }
        if (typeof numValue === 'number' && numValue > 0) {
          portfolioData.push({
            name: key,
            value: numValue,
            color: colorMap[key as keyof typeof colorMap] || '#6B7280'
          });
        }
      }

      return portfolioData;
    };

    const portfolioData = generatePortfolioData();

    // 如果没有数据，显示空状态
    if (portfolioData.length === 0) {
      return (
        <Card
          title={
            <Space>
              <DashboardOutlined className="text-purple-600" />
              <span>资产配置概览</span>
            </Space>
          }
          className="mb-4"
        >
          <div className="text-center py-8 text-gray-500">
            暂无资产配置数据
          </div>
        </Card>
      );
    }

    // 计算饼图路径
    const createPieChart = () => {
      const total = portfolioData.reduce((sum, item) => sum + item.value, 0);
      let currentAngle = 0;
      const radius = 80;
      const centerX = 120;
      const centerY = 120;

      const createArcPath = (startAngle: number, endAngle: number) => {
        const start = polarToCartesian(centerX, centerY, radius, endAngle);
        const end = polarToCartesian(centerX, centerY, radius, startAngle);
        const largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";

        return [
          "M", centerX, centerY,
          "L", start.x, start.y,
          "A", radius, radius, 0, largeArcFlag, 0, end.x, end.y,
          "Z"
        ].join(" ");
      };

      const polarToCartesian = (centerX: number, centerY: number, radius: number, angleInDegrees: number) => {
        const angleInRadians = (angleInDegrees - 90) * Math.PI / 180.0;
        return {
          x: centerX + (radius * Math.cos(angleInRadians)),
          y: centerY + (radius * Math.sin(angleInRadians))
        };
      };
 
      if (portfolioData.length === 1) {
        return (
          <svg width="240" height="240" viewBox="0 0 240 240" className="mx-auto">
            <circle
              cx={centerX}
              cy={centerY}
              r={radius}
              fill={portfolioData[0].color}
              stroke="white"
              strokeWidth="2"
            />
            <circle
              cx={centerX}
              cy={centerY}
              r="40"
              fill="white"
              stroke="#E5E7EB"
              strokeWidth="1"
            />
            <text
              x={centerX}
              y={centerY + 5}
              textAnchor="middle"
              className="fill-gray-700 text-base font-medium"
            >
              资产配置
            </text>
          </svg>
        );
      }

      const paths = portfolioData.map((item, index) => {
        const angle = (item.value / total) * 360;
        const path = createArcPath(currentAngle, currentAngle + angle);
        currentAngle += angle;

        return (
          <path
            key={index}
            d={path}
            fill={item.color}
            stroke="white"
            strokeWidth="2"
          />
        );
      });

      return (
        <svg width="240" height="240" viewBox="0 0 240 240" className="mx-auto">
          {paths}
          <circle
            cx={centerX}
            cy={centerY}
            r="40"
            fill="white"
            stroke="#E5E7EB"
            strokeWidth="1"
          />
          <text
            x={centerX}
            y={centerY + 5}
            textAnchor="middle"
            className="fill-gray-700 text-base font-medium"
          >
            资产配置
          </text>
        </svg>
      );
    };

    return (
      <Card
        title={
          <Space>
            <DashboardOutlined className="text-purple-600" />
            <span>资产配置概览</span>
          </Space>
        }
        className="mb-4"
      >
        <div className="flex flex-col items-center mb-6">
          {createPieChart()}

          {/* 图例 - 根据数据量动态调整布局 */}
          <div className={`grid gap-x-6 gap-y-2 mt-4 ${portfolioData.length <= 3 ? 'grid-cols-3' :
            portfolioData.length <= 6 ? 'grid-cols-3' : 'grid-cols-4'
            }`}>
            {portfolioData.map((item, index) => (
              <div key={index} className="flex items-center space-x-2">
                <div
                  className="w-4 h-4 rounded-sm"
                  style={{ backgroundColor: item.color }}
                />
                <span className="text-sm text-gray-700">
                  {item.name} {item.value}%
                </span>
              </div>
            ))}
          </div>
        </div>

        <Divider />

        <Row gutter={[12, 12]} className='mt-3'>
          <Col span={8}>
            <Statistic
              title="总资产"
              value={customer.aum_scale}
              valueStyle={{ color: '#1890ff', fontSize: '16px' }}
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="风险评分"
              value={customer.risk_score}
              suffix="分"
              valueStyle={{ color: '#52c41a', fontSize: '16px' }}
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="投资经验"
              value={customer.investment_experience}
              valueStyle={{ color: '#722ed1', fontSize: '16px' }}
            />
          </Col>
        </Row>
      </Card>
    );
  };

  // 投资行为分析卡片
  const renderInvestmentBehavior = () => (
    <Card
      title={
        <Space>
          <RiseOutlined className="text-orange-600" />
          <span>投资行为分析</span>
        </Space>
      }
      className="mb-4"
    >
      <Descriptions column={2} labelStyle={{ fontWeight: 'bold' }}>
        <Descriptions.Item label="平均持有期">
          {customer.average_holding_period}
        </Descriptions.Item>
        <Descriptions.Item label="交易频率">
          <Tag color='orange'>
            {customer.trading_frequency}
          </Tag>
        </Descriptions.Item>
        <Descriptions.Item label="投资时机">
          {customer.investment_timing}
        </Descriptions.Item>
        <Descriptions.Item label="亏损容忍度">
          <Tag color='orange'>
            {customer.loss_tolerance}
          </Tag>
        </Descriptions.Item>
      </Descriptions>

      <Divider orientation="left">偏好投资类别</Divider>
      <div className="flex flex-wrap gap-2 mt-2">
        {customer.preferred_investment_types?.map((category: string, index: number) => {
          // 去除每个元素中的中括号和所有引号
          const cleanCategory = category.replace(/^[\[\"]+|[\]\"]+$/g, '').replace(/"/g, '').trim();
          return (
            <Tag key={index} color="geekblue">{cleanCategory}</Tag>
          );
        })}
      </div>
    </Card>
  );

  // KYC信息卡片
  const renderKYCInfo = () => (
    <Card
      title={
        <Space>
          <FileTextOutlined className="text-green-600" />
          <span>KYC信息</span>
        </Space>
      }
      className="mb-4"
    >
      <Descriptions column={2} labelStyle={{ fontWeight: 'bold' }}>
        <Descriptions.Item label="教育水平">
          {customer.education_level}
        </Descriptions.Item>
        <Descriptions.Item label="年收入">
          {customer.annual_income_formatted}
        </Descriptions.Item>
        <Descriptions.Item label="投资目的">
          {customer.investment_goal}
        </Descriptions.Item>
        <Descriptions.Item label="投资期限">
          {customer.average_holding_period}
        </Descriptions.Item>
        <Descriptions.Item label="婚姻状况">
          {customer.marital_status}
        </Descriptions.Item>
        <Descriptions.Item label="金融知识">
          {customer.financial_knowledge_level}
        </Descriptions.Item>
        <Descriptions.Item label="风险承受能力">
          {customer.risk_level}
        </Descriptions.Item>
        <Descriptions.Item label="流动性需求">
          {customer.liquidity_preference}
        </Descriptions.Item>
        <Descriptions.Item label="合规状态">
          <Tag color={customer.compliance_status === '正常' ? 'green' : 'orange'}>
            {customer.compliance_status}
          </Tag>
        </Descriptions.Item>
        <Descriptions.Item label="更新时间">
          {customer.last_update_time}
        </Descriptions.Item>
      </Descriptions>
    </Card>
  );

  // 联系偏好卡片
  const renderContactPreferences = () => (
    <Card
      title={
        <Space>
          <PhoneOutlined className="text-blue-600" />
          <span>联系偏好</span>
        </Space>
      }
      className="mb-4"
    >
      <Descriptions column={2} labelStyle={{ fontWeight: 'bold' }}>
        <Descriptions.Item label="偏好联系渠道">
          <Tag color="blue">{customer.preferred_contact_channel}</Tag>
        </Descriptions.Item>
        <Descriptions.Item label="最佳联系时间">
          {customer.best_contact_time}
        </Descriptions.Item>
        <Descriptions.Item label="沟通频率">
          {customer.communication_frequency}
        </Descriptions.Item>
      </Descriptions>
    </Card>
  );

  // 最近产品卡片
  const renderRecentProducts = () => {
    const holdings = customer.fund_holdings || [];
    const displayHoldings = showAllHoldings ? holdings : holdings.slice(0, 2);
    const hasMoreHoldings = holdings.length > 2;

    return (
      <Card
        title={
          <Space>
            <TrophyOutlined className="text-purple-600" />
            <span>近期持仓</span>
          </Space>
        }
        className="mb-4"
      >
        <div className="space-y-4">
          {displayHoldings.map((product: any, index: number) => (
            <div key={index} className="border rounded-lg p-4">
              <div className="flex justify-between items-center mb-2">
                <div>
                  <Typography.Title level={5} className="!mb-1">
                    {product.fund_name}
                  </Typography.Title>
                  <Typography.Text type="secondary" className="text-sm">
                    {product.fund_code} • {product.fund_type}
                  </Typography.Text>
                </div>
                <div className="text-right">
                  <div className="text-lg font-medium text-gray-900">
                    ¥{formatAmount(product.holding_amount)}
                  </div>
                  <div className={`text-sm ${product.holding_profit >= 0 ? 'text-red-500' : 'text-green-500'}`}>
                    {product.holding_profit >= 0 ? '+' : ''}{product.holding_return_rate}
                  </div>
                </div>
              </div>
              <div className="flex justify-between text-sm text-gray-500">
                <span>持有份额: {product.holding_shares.toLocaleString()}</span>
                <span>单位净值: {product.unit_net_value}</span>
              </div>
            </div>
          ))}
          
          {hasMoreHoldings && (
            <div className="text-center pt-2">
              <Button 
                type="link" 
                onClick={() => setShowAllHoldings(!showAllHoldings)}
                icon={showAllHoldings ? <UpOutlined /> : <DownOutlined />}
              >
                {showAllHoldings ? '收起' : `展开查看全部 ${holdings.length} 条持仓`}
              </Button>
            </div>
          )}
        </div>
      </Card>
    );
  };

  return (
    <div className="h-full overflow-y-auto p-4 bg-gray-50">
      <div className="max-w-full mx-auto">
        {/* 页面标题 */}
        <div className="mb-4 pb-4">
          <div className="flex items-center space-x-3 mb-2">
            <Avatar size={40} style={{ backgroundColor: '#1890ff' }}>
              {customer.name[0]}
            </Avatar>
            <div>
              <h1 className="text-lg font-bold text-gray-800">{customer.name} - 客户画像</h1>
              <div className="flex items-center space-x-2 mt-1">
                <Tag color="blue">{customer.occupation}</Tag>
                <Tag color="green">{customer.investment_goal}</Tag>
                <Tag color="orange">{customer.risk_level}</Tag>
              </div>
            </div>
          </div>
        </div>

        {/* 主要内容区域 - 单列垂直布局 */}
        <div className="space-y-4">
          {/* AI总结 */}
          {renderAISummary()}

          {/* 资产配置概览 */}
          {renderAssetOverview()}

          {/* 投资行为分析 */}
          {renderInvestmentBehavior()}

          {/* 近期产品持有 */}
          {renderRecentProducts()}

          {/* KYC信息 */}
          {renderKYCInfo()}

          {/* 联系偏好 */}
          {renderContactPreferences()}
        </div>
      </div>
    </div>
  );
};

export default CustomerProfilePage; 